package com.example.java_second_hand_market;

import com.mysql.cj.log.NullLogger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import javafx.scene.control.*;

import java.sql.*;
import java.util.Iterator;
import java.util.Vector;

public class AddItemDialog extends Stage {
    Seller slr;
    BorderPane bp;
    Vector<String> tagvec=new Vector<>();
    String DBUrl1=ParameterDB.ParaDBUserUrl;
    String DBUser="root", DBPassword="123456";
    String taglist="";
    @FXML
    Label itemname=new Label("商品名称：");
    @FXML
    TextField itemfield=new TextField();
    @FXML
    Label pricelabel=new Label("价格：");
    @FXML
    TextField pricetext=new TextField();
    @FXML
    Label tags=new Label();
    @FXML
    Button addButton=new Button("+");
    @FXML
    Button delButton=new Button("-");
    @FXML
    TextField tagtext=new TextField();
    @FXML
    Button submit=new Button("添加");

    public AddItemDialog(Seller sel,int width,int height){
        slr=sel;
        addButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                tagaddaction();;
            }
        });
        delButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                tagdelaction();
            }
        });
        submit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                submitaction();
                CommonDialog.InformationDialog("添加成功");
            }
        });

        VBox vb = new VBox();
        vb.setSpacing(10);

        HBox hb1 = new HBox();
        hb1.getChildren().addAll(itemname, itemfield);
        hb1.setMargin(itemname, new Insets(3,0,0,0));
        hb1.setMargin(itemfield, new Insets(0,0,0,3));

        HBox hb2 = new HBox();
        hb2.getChildren().addAll(pricelabel, pricetext);
        hb2.setMargin(pricelabel, new Insets(3,0,0,0));
        hb2.setMargin(pricetext, new Insets(0,0,0,3));

        HBox hb3 = new HBox();
        hb3.getChildren().addAll(tagtext, delButton,addButton);
        hb3.setMargin(tagtext, new Insets(3,0,0,0));
        hb3.setMargin(delButton, new Insets(0,0,0,3));
        hb3.setMargin(delButton, new Insets(0,0,0,3));

        HBox hb4 = new HBox();
        hb4.getChildren().addAll( submit);
        hb4.setAlignment(Pos.CENTER);

        hb4.setMargin(submit, new Insets(0,0,0,3));

        vb.getChildren().addAll(hb1,hb2,tags,hb3);

        bp=new BorderPane();
        bp.setCenter(vb);
        bp.setBottom(hb4);
        bp.setPadding(new Insets(15,40,20,40));

        setX(820);
        setY(500);
        initModality(Modality.APPLICATION_MODAL);
        setScene(new Scene(bp));

        setWidth(700);
        setHeight(500);
        setX((width-getWidth()) / 2);
        setY((height-getHeight())/ 2);
        setTitle("添加商品");
    }
    public void tagaddaction(){
        if(tagtext.getText().length()>20){
            CommonDialog.WarningDialog("太长了！");
            tagtext.clear();
            return;
        }
        tagvec.add((tagtext.getText()).trim());
        if(taglist==null) {
            taglist=tagvec.lastElement();
        }else {
            taglist += ("," + tagvec.lastElement());
        }
        tags.setText(taglist);
    }
    public void tagdelaction(){
        if(tagvec.contains((tagtext.getText()).trim())){
            tagvec.remove((tagtext.getText()).trim());
            taglist= null;
            for(String i:tagvec){
                if(taglist==null){
                    taglist=i;
                }else{
                    taglist+=(","+i);
                }
            }
            tags.setText(taglist);
        }else{
            CommonDialog.WarningDialog("不存在该TAG！");
        }
    }
    public  void submitaction() {
        String name = (itemfield.getText());
        String price = (pricetext.getText()).trim();
        if(name.length()>20){
            CommonDialog.WarningDialog("名字太长了！");
            itemfield.clear();
            return;
        }
        if(!price.matches("^\\d+$")){
            CommonDialog.WarningDialog("请输入正确地价格");
            pricetext.clear();
            return;
        }
        if(price.length()>20){
            CommonDialog.WarningDialog("价格太高了！");
            pricetext.clear();
            return;
        }
        if (name != null && price != null) {
            try {
                   Connection con= DriverManager.getConnection(DBUrl1,DBUser,DBPassword);
                   Statement stmt=con.createStatement();
                   stmt.executeUpdate("INSERT INTO item_list (name, price, is_sold, seller, buyer) VALUES ('"+name+"', '"+price+"', 0, '"+slr.getName()+"', NULL);");
                if (!tagvec.isEmpty()) {


                        for (String i : tagvec) {
                            ResultSet rs1 = stmt.executeQuery("SELECT *   FROM tag_list where tag_name = '" + i+"'");
                            if (rs1.next()) {
                                int tagID = rs1.getInt("id");
                                ResultSet rs2=stmt.executeQuery("SELECT *   FROM item_list where name = '"+name+"'");
                                rs2.next();
                                int itemID=rs2.getInt("id");
                                stmt.executeUpdate("INSERT INTO tag_item_relation (Item_id,tag_id) VALUES ("+itemID+","+tagID+");");
                                if(rs2!=null) {
                                    try {
                                        rs2.close();


                                    } catch (SQLException err) {
                                        System.out.println("12");
                                    }
                                }
                            }else{
                                stmt.executeUpdate("INSERT INTO tag_list (tag_name) VALUES ('"+i+"');");
                                rs1 = stmt.executeQuery("SELECT *   FROM tag_list where tag_name = '" + i+"'");
                                rs1.next();
                                int tagID = rs1.getInt("id");
                                ResultSet rs2=stmt.executeQuery("SELECT *   FROM item_list where name = '"+name+"'");
                                rs2.next();
                                int itemID=rs2.getInt("id");
                                stmt.executeUpdate("INSERT INTO tag_item_relation (Item_id,tag_id) VALUES ("+itemID+","+tagID+");");
                                if(rs2!=null) {
                                    try {
                                        rs2.close();


                                    }catch (SQLException err){
                                        System.out.println("123");
                                    }
                                }
                            }
                            if(rs1!=null) {
                                try {
                                    rs1.close();


                                }catch (SQLException err){
                                    System.out.println("1234");
                                }
                            }
                        }


                }
                if(con!=null) {
                    try {

                        stmt.close();
                        con.close();

                    }catch (SQLException err){
                        System.out.println("12345");
                    }
                }

            }
            catch (SQLException s){
                System.out.println("不能打开 management， 数据库操作失败！"+s.getMessage()+s.getErrorCode()+s.getSQLState());
            }
        }
    }
    public BorderPane getBp(){
        return bp;
    }
}
